{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/awesome-bootstrap-checkbox.css' %}">
    <link rel="stylesheet" href="{% static 'css/dataTables.checkboxes.css' %}">
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/toastr.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <style>
        /*解决bootbox的边框BUG*/
        body {
            padding-right: 0 !important;
        }

        .dataTables_scrollBody {
            overflow-y: auto !important;
            overflow-x: hidden !important;
        }
        /* dataTables列内容居中 */
        #fort > tbody > tr > td {
            text-align: center;
            word-wrap: break-word;
        }

        /* dataTables表头居中 */
        #fort_wrapper table > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        .form-horizontal .form-group {
            margin-right: -200px;
        }

        #searchBox .form-group > label {
            margin-top: 5px; text-align: right; padding-right: 0px; padding-left: 0px;
        }

        #searchBox .form-group > .input-group {
            position: relative;
            left: 15px;
        }

        #buttonBar button {
            margin-right: 2px;
            margin-bottom: 5px;
        }

        .has-input-error {
            border: 1px solid #dd4b39;
        }

        .error-text {
            color: #dd4b39;
        }

        .button-item {
            text-align: center;
            margin-bottom: 10px;
        }

        .button-item button {
            width: 300px;
        }

        .toast-vertical-center {
            top:10%;
            left:30%;
        }

        @media screen and (min-width:1200px) and (max-width:1800px){
            label[for='asset_nu']{
                font-size:2px;
                line-height: 12px;
            }
        }

        td span.badge{
            white-space: pre-wrap;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="row" style="overflow-x: auto;">
        <div class="col-sm-7 pull-left" id="buttonBar" style="margin-bottom: 3px">
            {% if perms.fort.add_fortserver %}
                <button class="btn btn-sm btn-success pull-left" data-toggle="modal" id="add-fort-modal"
                        data-target="#FortModal">
                    <i class="fa fa-plus-square"></i>
                    <span class="bigger-110">新增主机</span>
                </button>
            {% endif %}
            <button class="btn btn-sm btn-info pull-left" id="advancedSearchBox">
                <i class="fa fa-search"></i>
                <span class="bigger-110">高级筛选</span>
            </button>
            <button class="btn btn-sm btn-info pull-left" style="display: none;" id="advancedSearch">
                <i class="fa fa-search"></i>
                <span class="bigger-110">点击筛选</span>
            </button>
            <button class="btn btn-sm btn-info pull-left" style="display: none;" id="refreshCondition">
                <i class="glyphicon glyphicon-trash"></i>
                <span class="bigger-110">清空筛选</span>
            </button>
            {% if perms.fort.add_fortserver and perms.fort.add_fortserveruser %}
            <button class="btn btn-sm btn-info pull-left" data-toggle="modal" data-target="#importFortModal" onclick="document.getElementById('import_fort_info').reset();">
                <i class="fa fa-upload"></i>
                <span class="bigger-110">批量导入</span>
            </button>
            {% endif %}
            {% if perms.fort.change_fortserveruser or perms.fort.delete_fortserver %}
                <div class="btn-group pull-left">
                    <button type="button" class="btn btn-primary btn-sm" style="margin-right: 0;">批量操作</button>
                    <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-left" role="menu">
                        {% if perms.fort.delete_fortserver %}
                            <li><a type="button" class="btn" id="batchDelete" style="text-align: left;"><i class="fa fa-trash-o"></i>批量删除</a></li>
                        {% endif %}
                        {% if perms.fort.change_fortserveruser %}
                            <li><a type="button" class="btn pull-left" id="batchAddUsers"><i class="fa fa-plus-square"></i>批量新增授权用户</a></li>
                            <li><a type="button" class="btn pull-left" id="batchDeleteUsers"><i class="fa fa-trash"></i>批量取消授权用户</a></li>
                            <li><a type="button" class="btn pull-left" id="batchAddGroup"><i class="fa fa-plus-square"></i>批量新增授权组</a></li>
                            <li><a type="button" class="btn pull-left" id="batchDeleteGroup"><i class="fa fa-trash"></i>批量取消授权组</a></li>
                        {% endif %}
                    </ul>
                </div>
            {% endif %}
        </div>

        <div class="modal fade" id="importFortModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Excel文件批量导入资产</h4>
                    </div>
                    {% if perms.fort.add_fortserver and perms.fort.add_fortserveruser %}
                        <div class="modal-body" style="margin-bottom: -10px;">
                            <div class="form-horizontal">
                                <div class="col-sm-12" style="line-height: 10px; margin-bottom: 10px;">注意：只支持导入主机、协议、账号同时唯一的信息！</div>
                                <div class="form-group" style="margin-right: -15px;">
                                    <label class="col-sm-2 control-label">导入模板</label>
                                    <div class="col-sm-6" style="margin-top: 3px;">
                                        <button type="button" class="btn btn-info btn-sm" onclick="window.location.href='/fort/download_fort_template'">下载<i class="fa fa-fw fa-download"></i></button></a>
                                    </div>
                                </div>
                                <form id="import_fort_info">
                                    <div class="form-group" style="margin-right: -15px;">
                                        <label class="col-sm-2 control-label">上传文件</label>
                                        <div class="col-sm-6" style="margin-top: 3px;">
                                            <input type="file" name="import_file" placeholder="上传excel文件" id="import_file"
                                                   accept=".csv,.xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="import_fort()">导入</button>
                        </div>
                    {% else %}
                        <div class="modal-body">
                            抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <form id="searchForm">
            <div class="col-md-12 col-lg-12 col-xs-12 pull-left" style="margin: 3px 0px 9px 0px;">
                <div id="searchBox" style="width: 99%; display: none;">
                    <div class="clearfix visible-xs"></div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="server_ip" class="col-lg-4 col-md-4 col-xs-3 control-label">管理IP</label>
                            <div class="col-lg-8 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="server_ip" name="server_ip">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_nu" class="col-lg-3 col-md-4 col-xs-3 control-label">资产编号/资产名称</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="asset_nu" name="asset_nu">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_username" class="col-lg-3 col-md-4 col-xs-3 control-label">账号</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="asset_username" name="asset_username">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="server_protocol" class="col-lg-4 col-md-4 col-xs-3 control-label">协议</label>
                            <div class="col-lg-8 col-md-8 col-xs-9">
                                <select class="form-control" id="server_protocol" style="width: 100%;" name="server_protocol">
                                        <option value=""></option>
                                    {% for protocol in server_protocols %}
                                        <option value="{{ protocol.0 }}">{{ protocol.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="server_status" class="col-lg-3 col-md-4 col-xs-3 control-label">状态</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                                <select class="form-control" id="server_status" style="width: 100%;" name="server_status">
                                        <option value=""></option>
                                    {% for status in server_status %}
                                        <option value="{{ status.0 }}">{{ status.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_environment" class="col-lg-3 col-md-4 col-xs-3 control-label">设备环境</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                              <select class="form-control" id="asset_environment" style="width: 100%;" name="asset_environment">
                                    <option value=""></option>
                                    {% for choice in asset_environment_ %}
                                        <option value="{{ choice.0 }}">{{ choice.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_product" class="col-lg-4 col-md-4 col-xs-3 control-label">产品名称</label>
                            <div class="col-lg-8 col-md-8 col-xs-9">
                                <select id="asset_product" style="display: none;" name="asset_product"></select>
                            </div>
                        </div>
                    </div>
                    <div class="clearfix visible-xs"></div>
                </div>
            </div>
        </form>
        {% if perms.fort.add_fortserver or perms.fort.change_fortserver  %}
        <!-- FortModal  -->
        <div class="modal fade" id="FortModal" tabindex="-1" role="dialog"
             aria-labelledby="FortModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;
                        </button>
                        <h4 class="modal-title" id="FortModalLabel">
                            新增主机
                        </h4>
                    </div>
                    <div class="modal-body">
                        <form id="add_fort" class="main form-horizontal">
                            <fieldset>
                                <div class="form-group">
                                    <label for="server" class="col-sm-2 control-label"><span class="text-red">*</span>主机</label>
                                    <div class="col-sm-6">
                                        <select class="form-control" id="server" name="server"
                                                style="width: 100%;">
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="add_server_protocol" class="col-sm-2 control-label">协议</label>
                                    <div class="col-sm-6">
                                        <select class="form-control" id="add_server_protocol" name="add_server_protocol" style="width: 100%;" onchange="protocolSelect(this);">
                                            {% for server_protocol in server_protocols %}
                                                <option value="{{ server_protocol.0 }}" {% ifequal server_protocol.0 'ssh' %}selected{% endifequal %}>{{ server_protocol.1 }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="add_server_status" class="col-sm-2 control-label">状态</label>
                                    <div class="col-sm-6">
                                        <select class="form-control" id="add_server_status" name="add_server_status" style="width: 100%;">
                                            {% for status in server_status %}
                                                <option value="{{ status.0 }}" {% ifequal status.0 1 %}selected{% endifequal %}>{{ status.1 }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="add_port" class="col-sm-2 control-label"><span class="text-red">*</span>连接端口</label>
                                    <div class="col-sm-6">
                                        <input type="number" class="form-control" name="add_port" id="add_port" value="22" min="1" max="99999" placeholder="1-99999之间" oninput="if(this.value=='0'){this.value='';}else{this.value=this.value.replace(/[^0-9]/g,'')};if(this.value.length>5){this.value=this.value.slice(0,5)};"/>
                                    </div>
                                </div>

                            </fieldset>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" id="add-fort">添加
                        </button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal -->
        </div>
        {% endif %}
        {% if perms.fort.add_fortserveruser or perms.fort.change_fortserveruser  %}
        <!-- FortUserModal  -->
        <div class="modal fade" id="FortUserModal" tabindex="-1"
             role="dialog"
             aria-labelledby="FortUserModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"
                                aria-hidden="true">
                            &times;
                        </button>
                        <h4 class="modal-title" id="FortUserModalLabel">
                            添加用户
                        </h4>
                    </div>
                    <div class="modal-body">
                        <form class="main form-horizontal" id="fort_user_info">
                            <fieldset>
                                <div class="form-group" style="display: none;">
                                    <label for="fort_server" class="col-sm-2 control-label"></label>
                                    <div class="col-sm-6">
                                        <input type="text" class="form-control" name="fort_server" id="fort_server"/>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="fort_username" class="col-sm-2 control-label">用户名称</label>
                                    <div class="col-sm-6">
                                        <input type="text" class="form-control" name="fort_username"
                                               id="fort_username" />
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="fort_user_status" class="col-sm-2 control-label">用户状态</label>
                                    <div class="col-sm-6">
                                        <select class="form-control" id="fort_user_status" name="fort_user_status" style="width: 100%;">
                                            {% for user_status in fort_user_status %}
                                                <option value="{{ user_status.0 }}" {% ifequal user_status.0 1 %}selected{% endifequal %}>{{ user_status.1 }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group" id="form-password">
                                    <label for="fort_password" class="col-sm-2 control-label">用户密码</label>
                                    <div class="col-sm-6">
                                        <input type="password" class="form-control" name="fort_password"
                                               id="fort_password"/>
                                    </div>
                                </div>

                                <div class="form-group" id="form-fort_code">
                                    <label for="fort_code" class="col-sm-2 control-label"><span class="text-red">*</span>字符编码</label>
                                    <div class="col-sm-6">
                                        <select class="form-control" id="fort_code" name="fort_code" style="width: 100%;">
                                            {% for code in fort_code_ %}
                                                <option value="{{ code.0 }}">{{ code.1 }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group" id="vnc_port">
                                    <label for="fort_vnc_port" class="col-sm-2 control-label"><span class="text-red">*</span>VNC端口</label>
                                    <div class="col-sm-6">
                                        <input type="number" class="form-control" name="fort_vnc_port"
                                               id="fort_vnc_port"  min="1" max="99999" placeholder="1-99999之间" oninput="if(this.value=='0'){this.value='';}else{this.value=this.value.replace(/[^0-9]/g,'')};if(this.value.length>5){this.value=this.value.slice(0,5)};"/>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="fort_belong_user" class="col-sm-2 control-label">所属用户</label>
                                    <div class="col-sm-6">
                                        <select class="form-control select2" id="fort_belong_user"
                                                multiple="multiple" name="fort_belong_user"
                                                style="width: 100%;">
                                            {% for user in users %}
                                                <option value="{{ user.id }}">{{ user.username }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="fort_belong_group" class="col-sm-2 control-label">所属组</label>
                                    <div class="col-sm-6">
                                        <select class="form-control select2" id="fort_belong_group"
                                                multiple="multiple" name="fort_belong_group"
                                                style="width: 100%;">
                                            {% for group in groups %}
                                                <option value="{{ group.id }}">{{ group.name }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="fort_user_memo" class="col-sm-2 control-label">用户说明</label>
                                    <div class="col-sm-6">
                                        <textarea class="form-control" id="fort_user_memo"
                                                  name="fort_user_memo"></textarea>
                                    </div>
                                </div>

                                <div class="space-24"></div>
                            </fieldset>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" id="fort_user_ops"></button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal -->
        </div>
        {% endif %}
        <!--dataTable-->
        <div class="col-xs-12">
            <div class="box" style="min-width: 1150px;">
                <div class="box-body">
                    <table id="fort" class="table table-bordered table-striped" style="width:100%; table-layout: fixed;">
                        <thead>
                        <tr>
                            <th></th>
                            <th>序号</th>
                            <th>管理IP</th>
                            <th>资产编号/资产名称</th>
                            <th>账号/VNC对象</th>
                            <th>协议</th>
                            <th>状态</th>
                            {% if perms.fort.change_fortserver or perms.fort.delete_fortserver or perms.fort.delete_fortserveruser or perms.fort.view_fort_password or perms.fort.change_fortserveruser %}<th>操作</th>{% endif %}
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>

{% endblock %}


{% block js %}
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <script src="{% static 'js/dataTables.checkboxes.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'js/bootbox.js' %}"></script>
    <script src="{% static 'js/toastr.min.js' %}"></script>
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script>
        $(function () {
            toastr.options = {
                "closeButton": true, //是否显示关闭按钮
                "positionClass": "toast-vertical-center",//弹出窗的位置
            }

            $('#asset_product').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                load: function(query, callback) {
                    $.ajax({
                        url: '/project/find_product_name/',
                        data: {
                            product_name: query
                        },
                        dataType: 'json',
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });

            var fort_server_table = $('#fort').DataTable({
                language: {
                   "sProcessing": "处理中...",
                   "sLengthMenu": "显示 _MENU_ 项结果",
                   "sZeroRecords": "没有匹配结果",
                   "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                   "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                   "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                   "sInfoPostFix": "",
                   "sSearch": "快速搜索:",
                   "searchPlaceholder": "管理IP 资产编号/资产名称",
                   "sUrl": "",
                   "sEmptyTable": "表中数据为空",
                   "sLoadingRecords": "载入中...",
                   "sInfoThousands": ",",
                   "oPaginate": {
                       "sFirst": "首页",
                       "sPrevious": "上页",
                       "sNext": "下页",
                       "sLast": "末页"
                   },
                   "oAria": {
                       "sSortAscending": ": 以升序排列此列",
                       "sSortDescending": ": 以降序排列此列"
                   }
               },
                sScrollY: 'calc(100vh - 400px)',
                columnDefs: [
                    {
                        'targets': 0,
                        'render': function (data, type, row, meta) {
                            if (type === 'display') {
                                data = '<div class="checkbox"><input type="checkbox" class="dt-checkboxes" value="'+row.id+'"><label></label></div>';
                            }
                            return data;
                        },
                        'orderable': false,
                        'checkboxes': {
                            'selectRow': true,
                        }
                    },
                    {
                        'targets': 1,
                        'render': function (data, type, row, meta) {
                            return row.id;
                        },
                    },
                    {
                        'targets': 2,
                        'render': function (data, type, row, meta) {
                            data = row.server.IP;
                            return data;
                        },
                    },
                    {
                        'targets': 3,
                        'render': function (d, type, row, meta) {
                            var data = ''
                            for(asset of row.asset){
                                data += '<span class="badge bg-aqua">'+asset.asset_nu+'</span>&nbsp;\n'
                            }
                            return data;
                        },
                        'orderable': false
                    },
                    {
                        'targets': 4,
                        'render': function (d, type, row, meta) {
                            var data = ''
                            for(fort_user of row.fortserveruser_set){
                                data += '<span style="margin-bottom:5px;" class="btn btn-xs '
                                if(fort_user.fort_user_status == 0){
                                    data += 'btn-danger'
                                } else {
                                    data += 'btn-primary'
                                }
                                data += ' update-fort-user" data-user-id="' + fort_user.id +
                                        '" data-server-id="' + row.server.id +
                                        '" data-protocol="' + row.server_protocol[0]+ '">'
                                if(row.server_protocol[0] == 'vnc'){
                                    data += fort_user.fort_vnc_port
                                    if(fort_user.fort_username){data += ' - '+fort_user.fort_username}
                                } else {
                                    data += fort_user.fort_username
                                }
                                data += '</span>&nbsp;\n'
                            }
                            {% if perms.fort.add_fortserveruser  %}
                                data += '<button style="margin-bottom:5px;" type="button" class="btn btn-info btn-xs add-fort-user" data-toggle="modal"\n' +
                                        ' data-target="#FortUserModal" data-server-id="'+row.server.id +
                                        '" data-fort-server="'+row.id+
                                        '" data-protocol="'+row.server_protocol[0]+'"><i class="fa fa-plus"></i>\n'+
                                        '</button>\n'
                            {% endif %}
                            return data
                        },
                        'orderable': false,
                    },
                    {
                        'targets': 5,
                        'render': function (data, type, row, meta) {
                            switch (row.server_protocol[0]){
                                case 'ssh':
                                    data = '<div class="badge bg-blue">'+row.server_protocol[1]+'</div>\n'
                                    break;
                                case 'telnet':
                                    data = '<div class="badge bg-teal">'+row.server_protocol[1]+'</div>\n'
                                    break;
                                case 'vnc':
                                    data = '<div class="badge bg-green">'+row.server_protocol[1]+'</div>\n'
                                    break;
                                case 'rdp':
                                    data = '<div class="badge bg-purple">'+row.server_protocol[1]+'</div>\n'
                                    break;
                            }
                            return data;
                        },
                    },
                    {
                        'targets': 6,
                        'render': function (data, type, row, meta) {
                            if(row.server_status[0]==0){
                                data = '<span class="badge bg-red">'+row.server_status[1]+'</span>'
                            } else {
                                data = '<span class="badge bg-green">'+row.server_status[1]+'</span>'
                            }
                            return data;
                        },
                    },
                    {% if perms.fort.change_fortserver or perms.fort.delete_fortserver or perms.fort.delete_fortserveruser or perms.fort.view_fort_password or perms.fort.change_fortserveruser %}
                    {
                        'targets': 7,
                        'render': function (data, type, row, meta) {
                            data = ''
                            {% if perms.fort.change_fortserver  %}
                            data += '<button type="button" class="btn btn-danger btn-xs disable_server" \n' +
                                'data-id="'+row.id+'">禁用</button>\n' +
                                '<button type="button" class="btn btn-info btn-xs enable_server" \n' +
                                'data-id="'+row.id+'">解禁</button>\n'
                            {% endif %}
                            {% if perms.fort.delete_fortserver  %}
                            data += '<button type="button" class="btn btn-danger btn-xs delete" \n' +
                                'data-id="'+row.id+'">删除</button>\n'
                            {% endif %}
                            data += '<div class="btn-group">\n' +
                                '<button type="button" class="btn btn-primary btn-xs">更多</button>\n' +
                                '<button type="button" class="btn btn-primary btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n' +
                                '<span class="caret"></span>\n' +
                                '</button>\n' +
                                '<ul class="dropdown-menu dropdown-menu-right" role="menu">\n'
                            {% if perms.fort.change_fortserver  %}
                                if(row.server_protocol[0] != 'vnc'){
                                    data += '<li><a onclick="fortPortChange(this);" data-id="'+row.id+'" data-server-protocol="'+row.server_protocol[0]+'">修改连接端口</a></li>\n'
                                }
                            {% endif %}
                            if(row.server_protocol[0] != 'vnc'){
                                {% if perms.fort.change_fortserveruser %}
                                    data += '<li><a onclick="usernameConnect(this,\'update\');" data-id="'+row.id+'" data-server-protocol="'+row.server_protocol[0]+'">更改用户信息</a></li>\n'
                                {% endif %}
                                {% if perms.fort.change_fortserveruser or perms.fort.view_fort_password %}
                                    data += '<li><a onclick="usernameConnect(this,\'search\');" data-id="'+row.id+'" data-server-protocol="'+row.server_protocol[0]+'">查看用户密码</a></li>\n'
                                {% endif %}
                                {% if perms.fort.change_fortserveruser %}
                                    data += '<li><a onclick="usernameConnect(this,\'reset\');" data-id="'+row.id+'" data-server-protocol="'+row.server_protocol[0]+'">修改用户密码</a></li>\n'
                                {% endif %}
                            } else {
                                {% if perms.fort.change_fortserveruser %}
                                    data += '<li><a onclick="usernameConnect(this,\'update\');" data-id="'+row.id+'" data-server-protocol="'+row.server_protocol[0]+'">更改VNC连接信息</a></li>\n'
                                {% endif %}
                                {% if perms.fort.change_fortserveruser or perms.fort.view_fort_password %}
                                    data += '<li><a onclick="usernameConnect(this,\'search\');" data-id="'+row.id+'" data-server-protocol="'+row.server_protocol[0]+'">查看VNC连接密码</a></li>\n'
                                {% endif %}
                                {% if perms.fort.change_fortserveruser %}
                                    data += '<li><a onclick="usernameConnect(this,\'reset\');" data-id="'+row.id+'" data-server-protocol="'+row.server_protocol[0]+'">修改VNC连接密码</a></li>\n'
                                {% endif %}
                            }
                            {% if perms.fort.delete_fortserveruser %}
                                if(row.server_protocol[0] == 'vnc') {
                                    data += '<li><a onclick="usernameConnect(this,\'delete\');" data-id="' + row.id + ' data-server-protocol="'+row.server_protocol[0]+'"">删除VNC连接信息</a></li>\n'
                                } else {
                                    data += '<li><a onclick="usernameConnect(this,\'delete\');" data-id="' + row.id + ' data-server-protocol="'+row.server_protocol[0]+'"">删除用户信息</a></li>\n'
                                }
                            {% endif %}
                            data += '</ul></div>\n'
                            return data;
                        },
                        'orderable': false
                    },
                    {% endif %}
                ],
                "infoCallback": function(settings,start,end,max,total,pre) {

                    var api = this.api();
                    var pageInfo = api.page.info();
                    return "共"+pageInfo.pages +"页,当前显示"+ start + "到" + end + "条记录" + ",共有"+ total + "条记录";
                },
                "order": [[1, "desc"]],
                "processing": true,
                "serverSide": true,
                "ajax": function (data, callback, settings) {
                    //console.log(data)
                    //封装请求参数
                    var param = {};
                    param.page_size = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                    param.start = data.start;//开始的记录序号
                    param.page = (data.start / data.length)+1;//当前页码
                    param.search = data.search.value;
                    var order = data.order[0]
                    var order_key = data.columns[order.column].data
                    $("#searchForm").serializeArray().forEach(function(el){
                        param[el['name']]= el['value']
                    })
                    if(order.dir=="asc"){
                        param.ordering = order_key
                    } else {
                        param.ordering = '-'+order_key
                    }
                    //ajax请求数据
                    $.ajax({
                        type: "GET",
                        url: "/api/fortlist/",
                        cache: false,  //禁用缓存
                        data: param,  //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //console.log(result);
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.results;//返回的数据列表
                            //console.log(returnData);
                            callback(returnData);
                        }
                    });
                },
                columns: [
                    { "data": 'id', "width": "30px" },
                    { "data": 'id', "width": "40px" },
                    { "data": "IP", "width": "200px"},
                    {  },
                    {  },
                    { "data": "server_protocol", "width": "100px" },
                    { "data": "server_status", "width": "100px" },
                    {% if perms.fort.change_fortserver or perms.fort.delete_fortserver or perms.fort.delete_fortserveruser or perms.fort.view_fort_password or perms.fort.change_fortserveruser %}{ "width": "200px" },{% endif %}
                ],
            });

            $("#refreshCondition").click(function () {
                $('#asset_product').selectize()[0].selectize.clear()
                $("#searchBox input,#searchBox select").val("")
            })

            $("#advancedSearchBox").click(function () {
                $("#refreshCondition").show()
                $("#advancedSearchBox").hide()
                $("#advancedSearch").show()
                $("#searchBox").show()
                toastr.info("使用SHIFT+回车键开启快捷筛选。")
            });

            $("#advancedSearch").click(function () {
                fort_server_table.draw(true);
            });

            $(document).keypress(function (e) {
                if(e.shiftKey&&e.keyCode==13){
                    fort_server_table.draw(true);
                }
            })

            $('.sidebar-toggle[data-toggle=push-menu]').click(function () {
                setTimeout(function(){
                    $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust()
                },500)
            })

            let fort_server_tbody = $('#fort tbody');
            // 删除主机
            fort_server_tbody.on('click', '.delete', function () {
                {% if perms.fort.delete_fortserver %}
                    let pk = $(this).attr('data-id');
                    let tr_obj = $(this).parents('tr');
                    $.confirm({
                        title: 'Tips',
                        content: '确定要删除这条记录么？',
                        type: 'red',
                        buttons: {
                            Ok: function () {
                                $.ajax({
                                    url: '/api/fort/' + pk + '/',
                                    method: 'DELETE',
                                    success: function () {
                                        $('#fort').DataTable().draw(true)
                                        $.alert({
                                            title: 'Tips',
                                            type: 'green',
                                            content: '删除成功！',
                                        })
                                    },
                                    error: function (data) {
                                        //console.log(data.responseText)
                                        $.alert({
                                            title: 'Tips',
                                            type: 'red',
                                            content: '删除失败！',
                                        })
                                    }
                                })
                            },
                            Cancel: function () {
                                //
                            }
                        }
                    });
                {% else %}
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '抱歉！您没有删除主机的权限！如有疑问，请联系管理员！',
                    });
                {% endif %}
            });
            {% if perms.fort.change_fortserver  %}
            // 禁用主机
            fort_server_tbody.on('click', '.disable_server', function () {
                let fort_server_id = $(this).attr('data-id');
                let fort_server_td_obj = $(this).parents('tr').children();
                $.ajax({
                    url: '/api/fort/' + fort_server_id + '/',
                    type: 'PATCH',
                    data: JSON.stringify({server_status: 0}),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function () {
                        fort_server_td_obj[6].innerHTML = '<span class="badge bg-red">禁用</span>'
                    },
                    error: function (response) {
                        //console.log(response.responseText)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: "禁用失败！",
                        })
                    }
                });
            });
            // 解禁主机
            fort_server_tbody.on('click', '.enable_server', function () {

                let fort_server_id = $(this).attr('data-id');
                let fort_server_td_obj = $(this).parents('tr').children();
                $.ajax({
                    url: '/api/fort/' + fort_server_id + '/',
                    type: 'PATCH',
                    data: JSON.stringify({server_status: 1}),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function () {
                        fort_server_td_obj[6].innerHTML = '<span class="badge bg-green">正常</span>'
                    },
                    error: function (response) {
                        //console.log(response.responseText)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: "解禁失败！",
                        })
                    }
                });
            });
            {% endif %}
            let fort_user_ops = $('#fort_user_ops');
            // 添加用户
            {% if perms.fort.add_fortserveruser  %}
            fort_server_tbody.on('click', '.add-fort-user', function () {
                cleanError()
                document.getElementById('fort_user_info').reset();
                $(".select2").val('').trigger('change');
                $('#fort_username').removeAttr("readonly");
                $('#form-password').css('display', '');
                let server_id = $(this).attr('data-server-id');
                let fort_server = $(this).attr('data-fort-server');
                let fort_protocol = $(this).attr('data-protocol');
                fort_user_ops.text('添加');

                if (new Array('ssh', 'telnet').includes(fort_protocol)) {
                    $('#FortUserModalLabel').text('新增用户');
                    $('#vnc_port').css('display', 'none');
                    $('label[for="fort_username"]').html("<span class=\"text-red\">*</span>用户名称")
                    $('#form-fort_code').css('display', 'block');
                    $('label[for="fort_user_status"]').html("<span class=\"text-red\">*</span>用户状态")
                    $('label[for="fort_password"]').html("<span class=\"text-red\">*</span>用户密码")
                    $('label[for="fort_user_memo"]').text("用户说明")
                    $('#fort_user_memo').attr('placeholder','')
                    fort_user_ops.unbind('click').on('click', function () {
                        cleanError()
                        let data = {
                            fort_server: fort_server,
                            fort_username: $('#fort_username').val(),
                            fort_password: $('#fort_password').val(),
                            fort_user_status: $('#fort_user_status').val(),
                            fort_user_memo: $('#fort_user_memo').val(),
                            fort_belong_user: $('#fort_belong_user').val(),
                            fort_belong_group: $('#fort_belong_group').val(),
                            fort_code: $('#fort_code').val()
                        };
                        $.ajax({
                            url: '/api/fort_user/',
                            type: 'POST',
                            data: JSON.stringify(data),
                            dataType: 'json',
                            contentType: "application/json",
                            success: function () {
                                $('#FortUserModal').modal('hide')
                                $('#fort').DataTable().draw(true)
                                $.alert({
                                    title: 'Tips',
                                    type: 'green',
                                    content: "新增成功！",
                                })
                            },
                            error: function (response) {
                                //console.log(response.responseText)
                                addFortServerErrorMessage(response.responseJSON)
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: "请修改错误！",
                                })
                            }
                        });
                    });
                } else if (fort_protocol === 'vnc') {
                    $('#FortUserModalLabel').text('新增VNC连接');
                    $('label[for="fort_user_status"]').html("<span class=\"text-red\">*</span>连接状态")
                    $('label[for="fort_password"]').text("连接密码")
                    $('label[for="fort_user_memo"]').text("连接说明")
                    $('#fort_user_memo').attr('placeholder','填写被连接服务器的登陆账号/密码等信息')
                    $('#vnc_port').css('display', 'block');
                    $('label[for="fort_username"]').text("连接对象")
                    $('#form-fort_code').css('display', 'none');
                    add_fort_user(server_id, fort_server)
                } else if (fort_protocol === 'rdp') {
                    $('#FortUserModalLabel').text('新增用户');
                    $('label[for="fort_user_status"]').html("<span class=\"text-red\">*</span>用户状态")
                    $('label[for="fort_password"]').html("<span class=\"text-red\">*</span>用户密码")
                    $('label[for="fort_user_memo"]').text("用户说明")
                    $('#fort_user_memo').attr('placeholder','')
                    $('#vnc_port').css('display', 'none');
                    $('label[for="fort_username"]').html("<span class=\"text-red\">*</span>用户名称")
                    $('#form-fort_code').css('display', 'none');
                    add_fort_user(server_id, fort_server)
                }
            });
            {% endif %}
            //修改用户信息选择框
            {% if perms.fort.change_fortserveruser or perms.fort.delete_fortserveruser or perms.fort.view_fort_password %}
            fort_server_tbody.on('click', '.update-fort-user', function () {
                let fort_user_id = $(this).attr('data-user-id');
                let fort_protocol = $(this).attr('data-protocol');
                var msg = ''
                if(fort_protocol == 'vnc'){
                    msg += {% if perms.fort.change_fortserveruser %}'<div class="button-item"><button type="button" class="btn btn-primary" onclick="updateFortUser('+fort_user_id+',\''+fort_protocol+'\');">更改VNC连接信息</button></div>\n' + {% endif %}
                        {% if perms.fort.change_fortserveruser or perms.fort.view_fort_password %}'<div class="button-item"><button type="button" class="btn btn-primary" onclick="searchFortUserPassword('+fort_user_id+');">查看VNC连接密码</button></div>\n'{% endif %}
                        {% if perms.fort.change_fortserveruser %}+ '<div class="button-item"><button type="button" class="btn btn-primary" onclick="updateFortUserPassword('+fort_user_id+');">修改VNC连接密码</button></div>\n'{% endif %}
                } else {
                    msg += {% if perms.fort.change_fortserveruser %}'<div class="button-item"><button type="button" class="btn btn-primary" onclick="updateFortUser('+fort_user_id+',\''+fort_protocol+'\');">更改用户信息</button></div>\n' + {% endif %}
                        {% if perms.fort.change_fortserveruser or perms.fort.view_fort_password %}'<div class="button-item"><button type="button" class="btn btn-primary" onclick="searchFortUserPassword('+fort_user_id+');">查看用户密码</button></div>\n'{% endif %}
                        {% if perms.fort.change_fortserveruser %}+ '<div class="button-item"><button type="button" class="btn btn-primary" onclick="updateFortUserPassword('+fort_user_id+');">修改用户密码</button></div>\n'{% endif %}
                }
                {% if perms.fort.delete_fortserveruser %}
                    msg += '<div class="button-item"><button type="button" class="btn btn-primary" onclick="deleteFortUser('+fort_user_id+');">'
                    if(fort_protocol == 'vnc'){
                        msg += '删除VNC连接信息'
                    } else {
                        msg += '删除用户信息'
                    }
                    msg += '</button></div>\n'
                {% endif %}
                bootbox.dialog({
                    title: '选项',
                    message: msg,
                    onEscape: true,
                    backdrop: true,
                    buttons: {
                        cancel: {
                            label: '关闭',
                            className: 'btn-danger',
                        },
                    }
                })
            })
            {% endif %}
        });

        {% if perms.fort.add_fortserver and perms.fort.add_fortserveruser %}
        // 导入连接管理
        function import_fort() {
            let formData = new FormData();
            let formFile = $('#import_file')[0].files[0]
            if(!formFile){
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: "请选择待上传的文件！",
                });
                return
            }
            formData.append('file', formFile);
            $.ajax({
                url: '/fort/import_fort/',
                type: 'POST',
                data: formData,
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType: false,
                success: function (responseStr) {
                    $.confirm({
                        title: 'Tips!',
                        content: responseStr.msg,
                        buttons: {
                            ok: function () {
                                window.location.reload();
                            },
                        }
                    });
                },
                error: function (responseStr) {
                    document.getElementById('import_fort_info').reset();
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: responseStr.responseJSON.msg,
                    });
                }
            });
        }
        {% endif %}

        // Initialize Select2 Elements
        function formatRepo (repo) {
            if (repo.loading) {
                return repo.text;
            }
            var $container = $("<div class='select2-result-repository clearfix'>" +
                  "<div class='select2-result-repository-element'>" + repo.text +
                "</div></div>");
            return $container;
        }

        function formatRepoSelection (repo) {
            return repo.text;
        }

        $(function () {
            $('.select2').select2({
                allowClear: true
            });

            $('#server').select2({
                allowClear: true,
                ajax: {
                    url: '/fort/find_custom_hosts/',
                    dataType: 'json',
                    data: function (params) {
                        params.offset = 6
                        params.page = params.page || 1
                        var query = {
                            search: params.term,
                            page: params.page,
                            offset: params.offset,
                        }
                        return query;
                    },
                    processResults: function (data, params) {
                        var page = params.page || 1;
                        return {
                            results: data.results,
                            pagination: {
                              more: (page*params.offset) < data.total_count
                            }
                        };
                    },
                    cache: true
                  },
                minimumInputLength: 2,
                templateResult: formatRepo,
                templateSelection: formatRepoSelection,
                placeholder: '查询IP地址 或 资产编号/资产名称',
            });
        });

        // 处理在modal中select2当选框无法搜索的问题
        $.fn.modal.Constructor.prototype.enforceFocus = function () {
        };

        //报错处理
        function addFortErrorMessage(errors) {
            if(errors.hasOwnProperty('server')){
                    $('#server').parent().append('<span class="help-block">'+errors.server+'</span>')
                    $('#server').next().addClass('has-input-error').parent().parent().addClass('has-error')
                }
            /*if(errors.hasOwnProperty('server_protocol')){
                    $('#add_server_protocol').parent().append('<span class="help-block">'+errors.server_protocol+'</span>')
                    $('#add_server_protocol').next().addClass('has-input-error').parent().parent().addClass('has-error')
                }*/
            if(errors.hasOwnProperty('port')){
                    $('#add_port').after('<span class="help-block">'+errors.port+'</span>')
                    $('#add_port').parent().parent().addClass('has-error')
                }

            if(errors.hasOwnProperty('non_field_errors')){
                    $('#add_server_protocol').parent().append('<span class="help-block">该连接已经存在，请更换连接协议。</span>')
                    $('#add_server_protocol').parent().parent().addClass('has-error')
                }
        }

        function addFortServerErrorMessage(errors) {
            console.log(errors)
            $.each(errors, function(name, value){
                if(name == 'non_field_errors'){
                    if($("#fort_vnc_port").is(':visible')){
                        $('#fort_username').after('<span class="help-block">该VNC连接已经存在，请修改!</span>')
                        $('#fort_username').parent().parent().addClass('has-error')
                        $('#fort_vnc_port').after('<span class="help-block">该VNC连接已经存在，请修改!</span>')
                        $('#fort_vnc_port').parent().parent().addClass('has-error')
                    } else{
                        $('#fort_username').after('<span class="help-block">该用户已经存在，请修改!</span>')
                        $('#fort_username').parent().parent().addClass('has-error')
                    }
                } else {
                    $.each(value, function(i, v){
                        $('#'+name).after('<span class="help-block">'+v+'</span>')
                    })
                    $('#'+name).parent().parent().addClass('has-error')
                }
            })
        }

        function cleanError(){
            $('.has-input-error').removeClass('has-input-error')
            $('.has-error').removeClass('has-error')
            $('.help-block').remove()
        }

        {% if perms.fort.add_fortserveruser  %}
        function add_fort_user(server_id, fort_server) {
            $('#fort_user_ops').unbind('click').on('click', function () {
                cleanError()
                if($('#fort_vnc_port').is(':visible') && $('#fort_vnc_port').val().length == 0){
                    $('#fort_vnc_port').after('<span class="help-block">该字段不能为空。</span>')
                    $('#fort_vnc_port').parent().parent().addClass('has-error')
                    return
                }
                let data = {
                    fort_server: fort_server,
                    fort_username: $('#fort_username').val(),
                    fort_password: $('#fort_password').val(),
                    fort_user_status: $('#fort_user_status').val(),
                    fort_user_memo: $('#fort_user_memo').val(),
                    fort_belong_user: $('#fort_belong_user').val(),
                    fort_belong_group: $('#fort_belong_group').val(),
                    fort_vnc_port: $('#fort_vnc_port').val(),
                    fort_code: '1'
                };
                $.ajax({
                    url: '/api/fort_user/',
                    type: 'POST',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function () {
                        $('#FortUserModal').modal('hide')
                        $('#fort').DataTable().draw(true)
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: "新增成功！",
                        })
                    },
                    error: function (response) {
                        //console.log(response.responseText)
                        addFortServerErrorMessage(response.responseJSON)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: "请修改错误！",
                        })
                    }
                });
            });
        }
        {% endif %}

        // 修改用户
        {% if perms.fort.change_fortserveruser  %}
        function updateFortUser(fort_user_id, fort_protocol){
            $('.bootbox').modal('hide')
            {% if perms.fort.view_fortserveruser  %}
            $('#FortUserModal').modal('show')
            cleanError()
            let fort_user_ops = $('#fort_user_ops');
            fort_user_ops.text('保存');
            $('#form-password').css('display', 'none');
            if (new Array('ssh', 'telnet').includes(fort_protocol)) {
                $('#fort_username').attr("readonly", "readonly");
                $('.modal-title').text('修改用户');
                $('#vnc_port').css('display', 'none');
                $('label[for="fort_username"]').html("<span class=\"text-red\">*</span>用户名称")
                $('#form-fort_code').css('display', 'block');
                $('label[for="fort_user_status"]').html("<span class=\"text-red\">*</span>用户状态")
                $('label[for="fort_password"]').html("<span class=\"text-red\">*</span>用户密码")
                $('label[for="fort_user_memo"]').text("用户说明")
                $('#fort_user_memo').attr('placeholder','')
            } else if (fort_protocol === 'vnc') {
                $('#fort_username').removeAttr("readonly");
                $('.modal-title').text('修改VNC连接');
                $('#vnc_port').css('display', 'block');
                $('label[for="fort_username"]').text("连接对象")
                $('#form-fort_code').css('display', 'none');
                $('label[for="fort_user_status"]').html("<span class=\"text-red\">*</span>连接状态")
                $('label[for="fort_password"]').text("连接密码")
                $('label[for="fort_user_memo"]').text("连接说明")
                $('#fort_user_memo').attr('placeholder','填写被连接服务器的登陆账号/密码等信息')
            } else if (fort_protocol === 'rdp') {
                $('#fort_username').attr("readonly", "readonly");
                $('.modal-title').text('修改用户');
                $('#vnc_port').css('display', 'none');
                $('label[for="fort_username"]').html("<span class=\"text-red\">*</span>用户名称")
                $('#form-fort_code').css('display', 'none');
                $('label[for="fort_user_status"]').html("<span class=\"text-red\">*</span>用户状态")
                $('label[for="fort_password"]').html("<span class=\"text-red\">*</span>用户密码")
                $('label[for="fort_user_memo"]').text("用户说明")
                $('#fort_user_memo').attr('placeholder','')
            }

            $.get('/api/fort_user/' + fort_user_id + '/', function (data) {
                $('#fort_username').val(data.fort_username);
                $('#fort_user_status').val(data.fort_user_status).trigger('change');
                $('#fort_belong_user').val(data.fort_belong_user).trigger('change');
                $('#fort_belong_group').val(data.fort_belong_group).trigger('change');
                $('#fort_user_memo').val(data.fort_user_memo);
                if(['ssh','telnet'].includes(fort_protocol)){
                    $('#fort_code').val(data.fort_code).trigger('change');
                }
                if (fort_protocol === 'vnc') {
                    $('#fort_vnc_port').val(data.fort_vnc_port)
                }
            });

            // 更新用户信息
            fort_user_ops.unbind('click').on('click', function () {
                cleanError()
                let data = {}
                if(fort_protocol === 'vnc'){
                    if($('#fort_vnc_port').val().length==0){
                        $('#fort_vnc_port').after('<span class="help-block">该字段不能为空。</span>')
                        $('#fort_vnc_port').parent().parent().addClass('has-error')
                        return
                    }
                    data.fort_username = $('#fort_username').val()
                }
                $.extend(data, {
                                fort_user_status: $('#fort_user_status').val(),
                                fort_belong_user: $('#fort_belong_user').val(),
                                fort_belong_group: $('#fort_belong_group').val(),
                                fort_user_memo: $('#fort_user_memo').val(),
                                fort_vnc_port: $('#fort_vnc_port').val()
                            }
                        )
                if(['ssh','telnet'].includes(fort_protocol)){
                    data.fort_code = $('#fort_code').val()
                }
                $.ajax({
                    url: '/api/fort_user/' + fort_user_id + '/',
                    type: 'PATCH',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function () {
                        $('#FortUserModal').modal('hide')
                        $('#fort').DataTable().draw(true)
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: "修改成功！",
                        })
                    },
                    error: function (response) {
                        //console.log(response.responseText)
                        addFortServerErrorMessage(response.responseJSON)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: "请修改错误！",
                        })
                    }
                });
            });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有查看堡垒机用户表的权限，如有问题请联系管理员！',
                });
            {% endif %}
        }
        {% endif %}
        // 删除用户
        {% if perms.fort.delete_fortserveruser  %}
        function deleteFortUser(fort_user_id){
            $('.bootbox').modal('hide')
            bootbox.confirm({
                size: "small",
                message: '确定要删除么？',
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-danger'
                    }
                },
                callback: function (result) {
                    var flag = true
                    if(result){
                        $.ajax({
                            url: '/api/fort_user/' + fort_user_id + '/',
                            async: false,
                            type: 'DELETE',
                            success: function () {
                                $('#fort').DataTable().draw(true)
                                $.alert({
                                    title: 'Tips',
                                    type: 'green',
                                    content: "删除成功！",
                                })
                            },
                            error: function (response) {
                                //console.log(response.responseText)
                                toastr.error('删除失败！')
                                flag = false
                            }
                        });
                        return flag
                    }
                }
            })
        }
        {% endif %}

        // 获取密码信息
        {% if perms.fort.change_fortserveruser or perms.fort.view_fort_password %}
        function searchFortUserPassword(fort_user_id){
            $('.bootbox').modal('hide')
            var content
            $.ajax({
                url: '/fort/search_fort_password/' + fort_user_id + '/',
                async: false,
                type: 'GET',
                success: function (result) {
                    content = '<p class="form-control-static" id="search_fort_password" style="width:100%;">当前密码：'+result.results.fort_password+'</p>'
                },
                error: function (response) {
                    //console.log(response.responseText)
                    toastr.error('获取失败！')
                }
            });
            bootbox.dialog({
                title: '密码信息',
                size: "small",
                message: content,
                buttons: {
                    cancel: {
                        label: '关闭',
                        className: 'btn-danger',
                    },
                }
            })
        }
        // 修改密码
        function updateFortUserPassword(fort_user_id){
            $('.bootbox').modal('hide')
            bootbox.confirm({
                title: '重置密码',
                size: "small",
                message: '<div style="margin-top: 5px;"><input type="password" class id="update_fort_password" style="width: 100%;" placeholder="请输入新的密码"></p></div>',
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-danger'
                    }
                },
                callback: function (result) {
                    var flag = true
                    if(result==true){
                        cleanError()
                        $('.error-text').remove()
                        $.ajax({
                            url: '/api/fort_user/' + fort_user_id + '/',
                            type: 'PATCH',
                            async: false,
                            data: JSON.stringify({
                                fort_password: $("#update_fort_password").val()
                            }),
                            dataType: 'json',
                            contentType: "application/json",
                            success: function (result) {
                                $.alert({
                                    title: 'Tips',
                                    type: 'green',
                                    content: "修改成功！",
                                })
                            },
                            error: function (response) {
                                //console.log(response.responseText)
                                toastr.error('请修改错误！')
                                if(response.responseJSON.hasOwnProperty('fort_password')){
                                    $('#update_fort_password').after('<span class="error-text">'+response.responseJSON.fort_password+'</span>')
                                    $('#update_fort_password').addClass('has-input-error')
                                }
                                flag = false
                            }
                        });
                        return flag
                    }
                }
            })
        }
        {% endif %}

        // 添加主机
        {% if perms.fort.add_fortserver %}
        $('#add-fort-modal').click(function () {
            $("#server").empty()
            document.getElementById('add_fort').reset();
            cleanError();
            $('#add-fort').off('click').on('click', function () {
                cleanError();
                let data = {
                    server: $('#server').val(),
                    server_protocol: $('#add_server_protocol').val(),
                    server_status: $('#add_server_status').val(),
                    port: $('#add_port').val()
                };
                $.ajax({
                    url: '/api/fort/',
                    type: 'POST',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function () {
                        $('#fort').DataTable().draw(true)
                        $('#FortModal').modal('hide')
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: "新增成功！",
                        })
                    },
                    error: function (response) {
                        addFortErrorMessage(response.responseJSON)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误！',
                        })
                    }
                });
            });
        });
        {% endif %}

        // 用户选择
        var userMessage = '<select id="fort_username" style="display: none;" name="fort_username" placeholder="请选择用户"></select>'
        function usernameSelect(fort_server_id){
           $('select#fort_username').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                placeholder: "请选择用户",
                preload: true,
                load: function(query, callback) {
                    $.ajax({
                        url: '/fort/find_username',
                        dataType: 'json',
                        data: {fort_server_id: fort_server_id},
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });
        }
        var vncMessage = '<select id="vnc_connect" style="display: none;" name="vnc_connect" placeholder="请选择VNC连接"></select>'
        function vncSelect(fort_server_id){
           $('select#vnc_connect').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                placeholder: "请选择VNC连接",
                preload: true,
                load: function(query, callback) {
                    $.ajax({
                        url: '/fort/find_vnc_connect',
                        dataType: 'json',
                        data: {fort_server_id: fort_server_id},
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });
        }
        function usernameConnect(ele, flag) {
            var fort_server_id = $(ele).attr('data-id')
            var server_protocol = $(ele).attr('data-server-protocol')
            if (server_protocol == 'vnc'){
                var fort_title = 'VNC连接选择'
                var fort_message =  '请选择VNC连接！'
                var fort_selection = vncMessage
            } else {
                var fort_title = '用户选择'
                var fort_message =  "请选择用户！"
                var fort_selection = userMessage
            }
            bootbox.dialog({
                title: fort_title,
                message: fort_selection,
                onEscape: true,
                backdrop: true,
                buttons: {
                    ok: {
                        label: '确认',
                        className: 'btn-primary',
                        callback: function(){
                            let fort_user_id = server_protocol=='vnc'?$('select#vnc_connect').val():$('select#fort_username').val()
                            if(fort_user_id.length==0){
                                toastr.error(fort_message)
                                return false
                            }
                            if(flag=='update'){
                                updateFortUser(fort_user_id, server_protocol)
                            } else if(flag=='search'){
                                searchFortUserPassword(fort_user_id)
                            } else if(flag=='reset'){
                                updateFortUserPassword(fort_user_id)
                            } else if(flag=='delete'){
                                deleteFortUser(fort_user_id)
                            }
                        }
                    },
                    cancel: {
                        label: '关闭',
                        className: 'btn-danger',
                    },
                }
            })
            server_protocol=='vnc'?vncSelect(fort_server_id):usernameSelect(fort_server_id)
        }

        function protocolSelect(ele){
            var type = $(ele).val()
            if(type == 'ssh'){
                $('#add_port').attr('placeholder','SSH连接默认端口为22').val(22).parent().parent().show()
            } else if(type == 'telnet'){
                $('#add_port').attr('placeholder','Telnet连接默认端口为23').val(23).parent().parent().show()
            } else if(type == 'rdp'){
                $('#add_port').attr('placeholder','RDP连接默认端口为3389').val(3389).parent().parent().show()
            } else{
                $('#add_port').val(5900).parent().parent().hide()
            }
        }

        // 修改端口
        {% if perms.fort.change_fortserver %}
        function fortPortMsg(initPort, type){
            var placeholder
            if(type == 'ssh'){
                placeholder = 'SSH连接默认端口为22'
                value = initPort||22
            } else if(type == 'telnet'){
                placeholder = 'Telnet连接默认端口为23'
                value = initPort||23
            } else {
                placeholder = 'RDP连接默认端口为3389'
                value = initPort||3389
            }
            return '<input type="number" class="form-control" name="port" id="port" min="1" value="'+value+'" max="99999" placeholder="'+placeholder+'" oninput="if(this.value==\'0\'){this.value=\'\';}else{this.value=this.value.replace(/[^0-9]/g,\'\')};if(this.value.length>5){this.value=this.value.slice(0,5)}">'
        }
        function fortPortChange(ele){
            var id = $(ele).attr('data-id')
            var type = $(ele).attr('data-server-protocol')
            var initPort
            if (type == 'vnc'){
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '不支持修改VNC协议的连接！',
                })
                return
            }
            $.ajax({
                    url: '/api/fort/' + id + '/',
                    type: 'GET',
                    async: false,
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (result) {
                        initPort = result.port
                    },
                    error: function (response) {
                        //console.log(response.responseText)
                    }
                });
            bootbox.dialog({
                    title: '修改连接端口',
                    message: fortPortMsg(initPort, type),
                    onEscape: true,
                    backdrop: true,
                    buttons: {
                        ok: {
                            label: '确认',
                            className: 'btn-primary',
                            callback: function(){
                                var port = $('#port').val()
                                if(port.length == 0){
                                    $('#port').parent().addClass('has-error')
                                    toastr.error('该字段不能为空!')
                                    return false
                                }
                                $.ajax({
                                    url: '/api/fort/' + id + '/',
                                    type: 'PATCH',
                                    data: JSON.stringify({
                                        port: port,
                                    }),
                                    dataType: 'json',
                                    contentType: "application/json",
                                    success: function (result) {
                                        $.alert({
                                            title: 'Tips',
                                            type: 'green',
                                            content: "修改成功！",
                                        })
                                    },
                                    error: function (response) {
                                        //console.log(response.responseText)
                                        $.alert({
                                            title: 'Tips',
                                            type: 'red',
                                            content: "修改失败！",
                                        })
                                    }
                                });
                            }
                        },
                        cancel: {
                            label: '关闭',
                            className: 'btn-danger',
                        },
                    }
                })
        }
        {% endif %}

        function checked() {
            let checkedID = [];
            var table = $('#fort').DataTable()
            var rows = $('#fort tbody>tr>td>div>input[type=checkbox]')
            $.each(rows, function (index, row) {
                if(row.checked == true){
                   checkedID.push(row.value)
                }
            })
            return checkedID;
        }
        // 批量删除
        {% if perms.fort.delete_fortserver %}
        $("#batchDelete").click(function () {
            let checkedID = checked();
            if (checkedID.length === 0) {
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '请选择要删除的连接！',
                })
            } else {
                var count = 0
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这些连接么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            for (let i = 0; i < checkedID.length; i++) {
                                $.ajax({
                                    url: '/api/fort/' + checkedID[i] + '/',
                                    method: 'DELETE',
                                    async: false,
                                    success: function () {
                                        count +=1
                                    }
                                })
                            }
                            $.confirm({
                                title: 'Tips',
                                content: '成功删除'+count+'个连接！',
                                type: 'green',
                                buttons: {
                                    Ok: function () {
                                        $('#fort').DataTable().draw(true)
                                    },
                                }
                            })
                        },
                        Cancel: function () {
                            // close
                        }
                    }
                })
            }
        });
        {% endif %}

        {% if perms.fort.change_fortserveruser %}
            $("#batchAddUsers").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的连接！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_add_fort_belong_user"\n' +
                        ' multiple="multiple" name="batch_add_fort_belong_user" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for user in users %}\n'+
                        ' <option value="{{ user.id }}">{{ user.username }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量新增授权用户',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_add_fort_belong_user").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_add_fort_belong_user').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                 for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/fort/batch_change_fort_belong_user/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'add',
                                            fort_id: checkedID[i],
                                            fort_belong_user: $("#batch_add_fort_belong_user").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += result.count
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个用户！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#fort').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_add_fort_belong_user").select2()
            })

            $("#batchDeleteUsers").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的连接！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_delete_fort_belong_user"\n' +
                        ' multiple="multiple" name="batch_delete_fort_belong_user" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for user in users %}\n'+
                        ' <option value="{{ user.id }}">{{ user.username }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量取消授权用户',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_delete_fort_belong_user").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_delete_fort_belong_user').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/fort/batch_change_fort_belong_user/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'delete',
                                            fort_id: checkedID[i],
                                            fort_belong_user: $("#batch_delete_fort_belong_user").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += result.count
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个用户！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#fort').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_delete_fort_belong_user").select2()

            })

            $("#batchAddGroup").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的连接！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_add_fort_belong_group"\n' +
                        ' multiple="multiple" name="batch_add_fort_belong_group" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for group in groups %}\n'+
                        ' <option value="{{ group.id }}">{{ group.name }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量新增授权组',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_add_fort_belong_group").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_add_fort_belong_group').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/fort/batch_change_fort_belong_group/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'add',
                                            fort_id: checkedID[i],
                                            fort_belong_group: $("#batch_add_fort_belong_group").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += result.count
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个用户！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#fort').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_add_fort_belong_group").select2()
            })

            $("#batchDeleteGroup").click(function () {
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择待修改的连接！',
                    })
                } else {
                    var count = 0
                    var msg = '<select class="form-control" id="batch_delete_fort_belong_group"\n' +
                        ' multiple="multiple" name="batch_delete_fort_belong_group" style="width: 100%;" data-placeholder="请选择">\n' +
                        ' {% for group in groups %}\n'+
                        ' <option value="{{ group.id }}">{{ group.name }}</option>\n' +
                        ' {% endfor %}</select>'
                    bootbox.confirm({
                        title: '批量取消授权组',
                        size: "small",
                        message: msg,
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result==true){
                                cleanError()
                                $('.error-text').remove()
                                if($("#batch_delete_fort_belong_group").val().length == 0){
                                    toastr.error('请修改错误！')
                                    $('#batch_delete_fort_belong_group').next().addClass('has-input-error').parent().after('<span class="error-text">该字段不能为空。</span>')
                                    return false
                                }
                                var count = 0
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/fort/batch_change_fort_belong_group/',
                                        type: 'POST',
                                        async: false,
                                        data: JSON.stringify({
                                            type: 'delete',
                                            fort_id: checkedID[i],
                                            fort_belong_group: $("#batch_delete_fort_belong_group").val()
                                        }),
                                        contentType: "application/json",
                                        success: function (result) {
                                            count += result.count
                                        }
                                    });
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '成功修改'+count+'个用户！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            $('#fort').DataTable().draw(true)
                                        },
                                    }
                                })
                            }
                        }
                    })
                }
                $("#batch_delete_fort_belong_group").select2()
            })
        {% endif %}
    </script>

{% endblock %}

